package worklog.db;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;


public class MyDB {
	public Connection connection;
	
	private String db_user = "";
	private String db_pass = "";
	private String db_name = "";
	
    public MyDB() throws Exception{
    	readDBproperties();
		try {
			Class.forName("com.mysql.jdbc.Driver");							// This will load the MySQL driver, each DB has its own driver
			connection = DriverManager.getConnection("jdbc:mysql://localhost/"+db_name, db_user, db_pass);
		}
		catch (Exception e) { throw e; }		
    }
    
    private void readDBproperties(){
    	Properties properties = new Properties();
    	FileInputStream file = null;
		try {
			file = new FileInputStream(MyDB.class.getClassLoader().getResource("").getPath() + "db.properties");
		} 
		catch (FileNotFoundException e) { e.printStackTrace(); }
		
    	try {
    		properties.load(file);
    	} 
    	catch (IOException e){
			//console.info(statement.toString());
    	}
    	db_user = properties.getProperty("db_user");
    	db_pass = properties.getProperty("db_pass");
    	db_name = properties.getProperty("db_name");
    }
    

	public void close(){
		try{
			connection.close();
		}
		catch(SQLException sqlException){
			sqlException.printStackTrace();
		}
	}
	
	protected void finalize(){ this.close(); }
}
